package com.cndongtai.util;

import java.util.Calendar;
import java.util.Date;

public class ByteUtil {

	public static int getUnsignedByte(byte data) { // 将data字节型数据转换为0~255 (0xFF 即BYTE)。
		return data & 0x0FF;
	}

	public static int getUnsignedByte(short data) { // 将data字节型数据转换为0~65535 (0xFFFF 即
												// WORD)。
		return data & 0x0FFFF;
	}

	public static long getUnsignedIntt(int data) { // 将int数据转换为0~4294967295
											// (0xFFFFFFFF即DWORD)。
		return data & 0x0FFFFFFFFl;
	}
	
	public static String hexStringFormat(String hexStr) {
		if(hexStr.length()==1) {
			return "0"+hexStr;
		}
		
		return hexStr;
	}
	
	public static byte[] getSysdateBytes() {
		byte[] dateBytes = new byte[7];
		
		Date date = new Date();
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		
		dateBytes[0] =  Long.valueOf(ca.get(Calendar.YEAR)%100).byteValue();
		dateBytes[1] =  Long.valueOf(ca.get(Calendar.MONTH)+1).byteValue();
		dateBytes[2] =  Long.valueOf(ca.get(Calendar.DATE)).byteValue();
		dateBytes[3] =  Long.valueOf(ca.get(Calendar.DAY_OF_WEEK)-1).byteValue();
		dateBytes[4] =  Long.valueOf(ca.get(Calendar.HOUR_OF_DAY)).byteValue();
		dateBytes[5] =  Long.valueOf(ca.get(Calendar.MINUTE)).byteValue();
		dateBytes[6] =  Long.valueOf(ca.get(Calendar.SECOND)).byteValue();
		
		return dateBytes;
	}
	
	public static int cal_crc(byte[] data, int len)
	{ 
		int i,num;
		int crc=0;
		for(num=0;num<len;num++)
		{
			for(i=0x80;i!=0;i>>=1)
			{
				if((crc&0x8000)!=0)
				{
					crc<<=1;
					crc^=0x1021;
				}else {
					crc<<=1;
				}
				if((data[num] & i)!=0x00) {
					crc^=0x1021;
				}
			}
		}

		crc = crc & 0xffff; 

		return crc;
	}
	
}
